<template>
  <div class="login-page">
    <div class="login-container">
      <!-- 左侧背景图 -->
      <div class="login-bg">
        <img src="/banner.jpg" alt="商城" />
      </div>

      <!-- 右侧登录表单 -->
      <div class="login-form-container">
        <div class="logo">
          <h1>欢迎登录</h1>
        </div>

        <el-tabs v-model="activeTab" class="login-tabs">
          <el-tab-pane label="登录" name="login">
            <el-form :model="loginForm" class="login-form">
              <el-form-item>
                <el-input
                  v-model="loginForm.username"
                  placeholder="邮箱/手机号码/用户名"
                  size="large"
                  clearable
                >
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="密码"
                  size="large"
                  show-password
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="loginForm.remember">
                  已阅读并同意<a href="#" class="link">使用协议</a>和<a href="#" class="link">隐私政策</a>
                </el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="large" class="login-btn" @click="handleLogin">
                  登录
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <el-tab-pane label="注册" name="register">
            <el-form :model="registerForm" class="login-form">
              <el-form-item>
                <el-input
                  v-model="registerForm.username"
                  placeholder="用户名"
                  size="large"
                  clearable
                >
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="registerForm.email"
                  placeholder="邮箱"
                  size="large"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Message /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="registerForm.phone"
                  placeholder="手机号"
                  size="large"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Phone /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="registerForm.password"
                  type="password"
                  placeholder="密码"
                  size="large"
                  show-password
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-input
                  v-model="registerForm.confirmPassword"
                  type="password"
                  placeholder="确认密码"
                  size="large"
                  show-password
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="registerForm.agree">
                  已阅读并同意<a href="#" class="link">使用协议</a>和<a href="#" class="link">隐私政策</a>
                </el-checkbox>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="large" class="login-btn" @click="handleRegister">
                  注册
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

        <div class="back-home">
          <el-button text @click="$router.push('/')">
            <el-icon><HomeFilled /></el-icon>
            返回首页
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Phone, HomeFilled } from '@element-plus/icons-vue'
import { useUserStore } from '../stores'
import request from '../utils/request'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const activeTab = ref('login')
const loginForm = ref({
  username: '',
  password: '',
  remember: false
})

const registerForm = ref({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  agree: false
})

// 登录
const handleLogin = async () => {
  if (!loginForm.value.username || !loginForm.value.password) {
    ElMessage.warning('请输入用户名和密码')
    return
  }

  if (!loginForm.value.remember) {
    ElMessage.warning('请阅读并同意使用协议和隐私政策')
    return
  }

  try {
    // 简化登录逻辑：根据用户名查找用户
    const res = await request.get('/users')
    console.log('用户列表响应:', res)
    console.log('用户数据:', res.data)
    
    const user = res.data.find(u => 
      u.username === loginForm.value.username || 
      u.email === loginForm.value.username ||
      u.phone === loginForm.value.username
    )

    console.log('找到的用户:', user)
    console.log('输入的密码:', loginForm.value.password)
    console.log('用户的密码:', user ? user.password : '未找到用户')

    if (user && user.password === loginForm.value.password) {
      // 登录成功
      userStore.login({
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone
      })
      
      ElMessage.success('登录成功！')
      
      // 如果有重定向地址，跳转到重定向地址
      const redirect = route.query.redirect || '/'
      router.push(redirect)
    } else {
      if (!user) {
        ElMessage.error('用户不存在')
      } else {
        ElMessage.error('密码错误')
      }
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error('登录失败，请重试')
  }
}

// 注册
const handleRegister = async () => {
  if (!registerForm.value.username || !registerForm.value.email || 
      !registerForm.value.phone || !registerForm.value.password) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    ElMessage.warning('两次密码输入不一致')
    return
  }

  if (!registerForm.value.agree) {
    ElMessage.warning('请阅读并同意使用协议和隐私政策')
    return
  }

  try {
    // 先检查用户名和邮箱是否已存在
    const checkRes = await request.get('/users')
    const existingUser = checkRes.data.find(u => 
      u.username === registerForm.value.username || 
      u.email === registerForm.value.email
    )

    if (existingUser) {
      if (existingUser.username === registerForm.value.username) {
        ElMessage.error('该用户名已被使用，请换一个')
      } else {
        ElMessage.error('该邮箱已被注册，请换一个')
      }
      return
    }

    // 注册新用户
    await request.post('/users', {
      username: registerForm.value.username,
      email: registerForm.value.email,
      phone: registerForm.value.phone,
      password: registerForm.value.password
    })

    ElMessage.success('注册成功！请登录')
    activeTab.value = 'login'
    loginForm.value.username = registerForm.value.username
    // 清空注册表单
    registerForm.value = {
      username: '',
      email: '',
      phone: '',
      password: '',
      confirmPassword: '',
      agree: false
    }
  } catch (error) {
    console.error('注册错误:', error)
    ElMessage.error('注册失败，请重试')
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 2vh 0;
}

.login-container {
  display: flex;
  width: 85%;
  max-width: 1100px;
  height: 80vh;
  max-height: 650px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.login-bg {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.login-bg img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.login-form-container {
  width: 100%;
  max-width: 480px;
  padding: 3vh 50px;
  display: flex;
  flex-direction: column;
  background: white;
  overflow-y: auto;
}

.logo {
  text-align: center;
  margin-bottom: 2vh;
}

.logo h1 {
  color: #E02E24;
  font-size: 28px;
  margin: 0;
  font-weight: 500;
}

.login-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.login-tabs :deep(.el-tabs__header) {
  margin-bottom: 2vh;
  flex-shrink: 0;
}

.login-tabs :deep(.el-tabs__item) {
  font-size: 16px;
  padding: 0 25px;
}

.login-tabs :deep(.el-tabs__active-bar) {
  background-color: #E02E24;
}

.login-tabs :deep(.el-tabs__item.is-active) {
  color: #E02E24;
}

.login-tabs :deep(.el-tabs__content) {
  flex: 1;
  overflow-y: auto;
}

.login-form {
  padding-top: 1vh;
}

.login-form :deep(.el-input__wrapper) {
  padding: 10px 15px;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 1.5vh;
}

.login-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  background: linear-gradient(to right, #E02E24, #FF4433);
  border: none;
  border-radius: 4px;
  margin-top: 0.5vh;
}

.login-btn:hover {
  background: linear-gradient(to right, #FF4433, #E02E24);
}

.form-footer {
  text-align: center;
  margin-top: 1vh;
  flex-shrink: 0;
}

.link {
  color: #E02E24;
  text-decoration: none;
  font-size: 13px;
}

.link:hover {
  text-decoration: underline;
}

.back-home {
  text-align: center;
  margin-top: 1.5vh;
  flex-shrink: 0;
}

.back-home :deep(.el-button) {
  color: #666;
  font-size: 14px;
}

.back-home :deep(.el-button:hover) {
  color: #E02E24;
}

/* 响应式 */
@media (max-width: 1024px) {
  .login-container {
    width: 90%;
    height: 85vh;
    max-height: none;
  }

  .login-bg {
    display: none;
  }

  .login-form-container {
    max-width: 100%;
    padding: 3vh 40px;
  }
}

@media (max-width: 768px) {
  .login-page {
    padding: 0;
  }

  .login-container {
    width: 100%;
    height: 100vh;
    border-radius: 0;
  }

  .login-form-container {
    padding: 3vh 20px;
  }
}
</style>

